<script setup>
import { ref, onMounted } from 'vue'
const input = ref('')
const msgs = ref([])
let ws = null

onMounted(() => {
  ws = new WebSocket('ws://127.0.0.1:8080')
  ws.onopen = () => msgs.value.push({t:'sys', m:'已连接'})
  ws.onmessage = e => msgs.value.push({t:'recv', m:e.data})
  ws.onclose = () => msgs.value.push({t:'sys', m:'连接关闭'})
  ws.onerror = e => {
    console.error('WebSocket 错误:', e)
    msgs.value.push({t:'sys', m:'连接错误 - 检查控制台'})
  }
})

const send = () => {
  if (ws?.readyState === 1 && input.value) {
    ws.send(input.value)
    msgs.value.push({t:'send', m:input.value})
    input.value = ''
  }
}
</script>

<template>
  <div style="max-width:600px;margin:2rem auto;">
    <h2>Vue ↔ C</h2>
    <div style="height:300px;overflow:auto;border:1px solid #ccc;padding:1rem;background:#f9f9f9;">
      <div v-for="(x,i) in msgs" :key="i"
           :style="x.t==='send'?{textAlign:'right',color:'#1976d2'}:
                   x.t==='recv'?{textAlign:'left',color:'#2e7d32'}:
                   {textAlign:'center',color:'#999',fontStyle:'italic'}">
        {{ x.m }}
      </div>
    </div>
    <input v-model="input" @keyup.enter="send" placeholder="输入…" style="width:80%;padding:0.5rem;" autofocus />
    <button @click="send" style="padding:0.5rem 1rem;">发送</button>
  </div>
</template>
